import java.net.*;
import java.io.*;

public class Connect {
    private static Socket socket;
    private static BufferedReader input;
    private static PrintWriter output;
    private static boolean isConnected = false;

    private Connect() {
        throw new IllegalStateException("Utility class");
    }

    public static Socket getSocket() {
        return socket;
    }

    public static void setSocket(Socket link) {
        Connect.socket = link;
    }

    public static boolean getIsConnected() {
        return isConnected;
    }

    static class Listens extends Thread {
        private int listensPort;

        public Listens(int listensPort) {
            this.listensPort = listensPort;
        }

        @Override
        public void run() {
            try (ServerSocket svr = new ServerSocket(listensPort)) {
                System.out.println(this.toString() + "> 等待服务器连接……");
                Socket clt = svr.accept();
                setSocket(clt);
                connect();
                System.out.println(this.toString() + "> 服务器连接成功!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private static void connect() throws IOException {
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream());
            isConnected = true;
        }
    }

    public static void println(String s) throws IOException {
        if (!isConnected) {
            throw new IOException("未成功连接.");
        }
        output.println(s);
        output.flush();
        System.out.println("send\t=>\t" + s);
    }

    public static String readLine() throws IOException {
        if (!isConnected) {
            throw new IOException("未成功连接.");
        }
        String read = input.readLine();
        System.out.println("receive\t<=\t" + read);
        return read;
    }

    public static void close() {
        try {
            socket.close();
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
